package com.sys.tool;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.*;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;


/**
 * Created by IntelliJ IDEA.
 * User: mabo
 * Date: 2009-10-20
 * Time: 16:31:33
 * To change this template use File | Settings | File Templates.
 */
public class HttpClientSuperTool {
    HttpParams params = new BasicHttpParams();

    BasicHttpProcessor httpproc = new BasicHttpProcessor();

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);

    HttpHost host;


    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    BasicHttpRequest request;
    HttpResponse response;

    public HttpClientSuperTool() {
        // HTTP 协议的版本,1.1/1.0/0.9
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
// 字符集
        HttpProtocolParams.setContentCharset(params, "GB2312");
// 伪装的浏览器类型
// IE7 是
// Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)
//
// Firefox3.03
// Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3
//
        HttpProtocolParams.setUserAgent(params, "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)");
        HttpProtocolParams.setUseExpectContinue(params, true);

        httpproc.addInterceptor(new RequestContent());
        httpproc.addInterceptor(new RequestTargetHost());

        httpproc.addInterceptor(new RequestConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());


    }


    public void setHost(String hostname) {
        host = new HttpHost(hostname, 80);
    }

    public void setHost(String hostname, int port) {
        host = new HttpHost(hostname, port);
    }

    /**
     * @param uri 去除域名后的部分
     * @throws IOException
     */
    public void execute(String uri) {
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
        if (!conn.isOpen()) {
            try {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            } catch (IOException e) {
                //e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

        }

        request = new BasicHttpRequest("GET", uri);
        context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
        request.setParams(params);
        try {
            httpexecutor.preProcess(request, httpproc, context);
            response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);
        } catch (HttpException e) {
            //e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            //e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    public String getHtmlBody() {
        return getHtmlBody("GB2312");
    }

    /**
     * @param defaultCharset 字符集编码
     * @return
     * @throws IOException
     */
    public String getHtmlBody(String defaultCharset){
        try {
            return EntityUtils.toString(response.getEntity(), defaultCharset);
        } catch (IOException e) {
            //e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            return "";
        }
    }

    public void close() {
        if (!connStrategy.keepAlive(response, context)) {
            try {
                conn.close();
            } catch (IOException e) {
                //e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        } else {
            System.out.println("Connection kept alive...");
        }
    }

    public static void main(String[] args) {
        HttpClientSuperTool hcst = new HttpClientSuperTool();
        hcst.setHost("search.51job.com");
        hcst.execute("/jobsearch/search_result.php?fromJs=1&jobarea=0100&district=0000&funtype=2606%2C0106%2C0147%2C2501%2C2503&industrytype=01%2C40%2C32%2C39%2C42&issuedate=9&providesalary=99&keyword=Java&keywordtype=2&curr_page=2&lang=c&stype=2&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=0&lonlat=0%2C0&radius=-1&ord_field=0&list_type=0&fromType=14");
        System.out.println(hcst.getHtmlBody());
        
        hcst.execute("/jobsearch/search_result.php?fromJs=1&jobarea=0100&district=0000&funtype=2606%2C0106%2C0147%2C2501%2C2503&industrytype=01%2C40%2C32%2C39%2C42&issuedate=9&providesalary=99&keyword=Java&keywordtype=2&curr_page=1&lang=c&stype=2&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=0&lonlat=0%2C0&radius=-1&ord_field=0&list_type=0&fromType=14");
        System.out.println(hcst.getHtmlBody());

    }
}